package com.zxl.muban.util;

import cn.hutool.extra.spring.SpringUtil;
import com.zxl.muban.entity.User;
import com.zxl.muban.service.RoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.authc.LogoutAware;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisSessionDAO;

import java.util.Collection;
import java.util.Objects;

/**
 * Shiro工具类
 */
public class ShiroUtils {

	/** 私有构造器 **/
	private ShiroUtils(){ }

    private static RedisSessionDAO redisSessionDAO = SpringUtil.getBean(RedisSessionDAO.class);

	private static RoleService roleService = SpringUtil.getBean(RoleService.class);

    /**
     * 获取当前用户Session
     */
    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    /**
     * 用户退出登录
     */
    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

	/**
	 * 获取当前用户信息
	 */
	public static User getUserInfo() {
		return (User) SecurityUtils.getSubject().getPrincipal();
	}

    /**
     * 获取当前用户id
     */
    public static Long getUserId() {
        return getUserInfo().getId();
    }

    /**
     * 删除用户缓存信息
     * @Param  loginName 用户登录名称
     * @Param  loginType 当前登录的登录方式（mobile 移动端登录，web PC端登录）
     */
    public static void deleteCache(String loginName, String loginType){
        //从缓存中获取Session
        Session session = null;
        Collection<Session> sessions = redisSessionDAO.getActiveSessions();
        User sysUserEntity;
        Object attribute = null;
        for(Session sessionInfo : sessions){
            //遍历Session,找到该用户名称对应的Session
            attribute = sessionInfo.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (attribute == null) {
                continue;
            }
            System.out.println(((SimplePrincipalCollection) attribute).getPrimaryPrincipal());
            sysUserEntity = (User) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal();
            if (sysUserEntity == null) {
                continue;
            }
            if (Objects.equals(sysUserEntity.getPhone(), loginName)) {
                session=sessionInfo;
                break;
            }
        }
        if (session == null||attribute == null) {
            return;
        }
        /**
         * 根据当前登录类型，在attribute中查找上一次登录的Realm，
         *      1、如果有值，说明当前登录的终端和上一次登录的终端相同，则删除上一次登录的session（清空上一次的登录信息，重新登录）。
         *      2、如果没有值，说明当前登录的终端和上一次登录的终端不一样，不对上一次登录的session删除，实现app端和web端可同时在线
         */
        Collection collection = ((SimplePrincipalCollection) attribute).fromRealm(loginType);
        if (!collection.isEmpty()){
            //删除session
            redisSessionDAO.delete(session);
        }
        //删除Cache，在访问受限接口时会重新授权
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        Authenticator authc = securityManager.getAuthenticator();
        ((LogoutAware) authc).onLogout((SimplePrincipalCollection) attribute);
    }

}
